import { ControlBase } from './controlbase';
import { DynamicFormService } from './dynamic-form-service';
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
    selector: 'dynamic-form',
    templateUrl: './dynamic-form.component.html',
    styleUrls: ['./dynamic-form.component.scss'],
    providers: [DynamicFormService]
})
export class DynamicFormComponent {
    @Input() formName = '';

    private _ctrls: ControlBase<any>[] = [];

    public isLoading: boolean = true;
    // @Input() ctrls: ControlBase<any>[] = [];
    @Input()
    get ctrls() {
        return this._ctrls;
    }
    set ctrls(value) {
        console.log('%c setting', 'color: green;');
        if (!value) {
            this._ctrls = [];
        } else {
            this._ctrls = value;
        }
    }

    form: FormGroup;

    _payLoad: string = '';

    @Output()
    getPlayLoad: EventEmitter<FormGroup> = new EventEmitter<FormGroup>(true);

    constructor(private ctrl: DynamicFormService) {}

    ngOnInit() {
        // 为了兼容二维数组
        let initValues = {};

        this.ctrls.map((ctrl: any) => {
            if (ctrl.length) {
                ctrl.forEach(c => {
                    initValues[c.key] = c.value;
                });
            } else {
                initValues[ctrl.key] = ctrl.value;
            }
            console.log(`%c kv value is${initValues}`, 'color: orange');
        });

        this.form = this.ctrl.toFormGroup(this.ctrls);
        if (this.ctrls.length) {
            this.form.patchValue(initValues);
            this.form.valueChanges.subscribe(data => this.onValueChanged(data));
        }
    }

    ngAfterViewInit() {
        console.log('ngAfterViewChecked');
        console.log(this.isLoading);
        setTimeout(() => {
            this.isLoading = false;
        }, 1500);
    }

    onValueChanged(data?: any) {
        this.getPlayLoad.emit(this.form.value);
    }

    ngOnChanges(...args: any[]) {
        console.log('%c........onChange fired', 'color: yellow;');
        console.log('changing', args);
        if (!args[0].ctrls.currentValue && !this.ctrls.length) {
            return;
        }
        this.ctrls = args[0].ctrls.currentValue;

        this.ngOnInit();
    }

    onSubmit() {
        this._payLoad = JSON.stringify(this.form.value);
    }
}
